"""The base Controller API

Provides the BaseController class for subclassing.
"""
from pylons.controllers import WSGIController
from pylons.templating import render_mako as render
from pylons.controllers.util import abort
from pylons import request, response, session, tmpl_context as c
import pythonblog.lib.helpers as h
from pythonblog.model import meta

class MenuInfo(object):
    pass

class BaseController(WSGIController):

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
    
    def get_sub_domain(self, environ):
        return environ['pylons.routes_dict'].get('sub_domain')

    def get_action(self, environ):
        return environ['pylons.routes_dict'].get('action')

    def validate(self, userName, environ):
        if not (h.auth.authorized(h.auth.is_valid_user) and userName == environ['REMOTE_USER']):
            abort(401)

    def _get_page(self):
        try:
            return int(request.params.get('page', 1))
        except:
            return 1

    def _set_cookie(self, name, value):
        response.set_cookie(name, value, path='/', domain=h.domain, max_age=3600*24*30)

    def _delete_cookie(self, name):
        response.delete_cookie(name, path='/', domain=h.domain)

    def _set_menu(self, section_path='all', post_type='all',
                  rank_type='new', time_duration='recent'):
        menu = MenuInfo()
        menu.section_path = section_path
        menu.post_type = post_type
        menu.rank_type = rank_type
        menu.time_duration = time_duration
        c.menu = menu

    def _is_home(self, sub_domain):
        if (sub_domain is None) or (sub_domain == 'www'):
            return True
        return False
    